﻿using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Cobalt.Framework.Graphics
{

	public sealed class TextFormatter : ITextFormattingHandler
	{
		private static Color[] colors = new Color[]
			{
				Color.Red,
				Color.Orange,
				Color.Yellow,
				Color.LightGreen,
				Color.CornflowerBlue,
				Color.Violet,
				Color.Black,
				Color.DarkGray,
				Color.Gray,
				Color.White,
			};

		#region ITextFormattingHandler Members

		public int HandleFormattingSequence( TextSource text, int position, FormattingStack stack )
		{
			if( text.Count - position < 2 )
				return position;

			if( text[position] != '\f' )
				return position;

			if( text[position + 1] == '-' )
			{
				if( stack != null )
					stack.Pop();
				return position + 2;
			}
			if( text[position + 1] == '#' )
			{
				if( text.Count - position < 8 )
					return position;

				int r = Helpers.ParseHex( text, position + 2, 2 );
				if( r < 0 )
					return 0;
				int g = Helpers.ParseHex( text, position + 4, 2 );
				if( g < 0 )
					return 0;
				int b = Helpers.ParseHex( text, position + 6, 2 );
				if( b < 0 )
					return 0;

				if( stack != null )
					stack.PushColor( new Color( (byte)r, (byte)g, (byte)b, stack.Color.A ) );

				return position + 8;
			}
			else if( text[position + 1] >= '0' && text[position + 1] <= '9' )
			{
				if( stack != null )
				{
					Color cl = colors[text[position + 1] - '0'];
					stack.PushColor( new Color( cl.R, cl.G, cl.B, stack.Color.A ) );
				}

				return position + 2;
			}

			return position;
		}

		#endregion
	}
}